<?php

namespace core\lib;

/**
 * 路由类
 */
class Route
{
    public $ctrl;
    public $action;

    function __construct()
    {
        $default = 'index';
        $this->ctrl = 'tool';
        $this->action = $default;
        if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/') {
            $requestMethod = strtoupper($_SERVER['REQUEST_METHOD']);
            $patharr = explode("?", $_SERVER['REQUEST_URI']);
            $path = $patharr[0];
            $patharr = array_filter(explode('/', trim($path, '/')));
            if (!in_array($requestMethod, ['GET', 'POST'])) {
                error('不支持的请求方式', 400);
            }
            if ($patharr[0] === 'static') {
                return;
            }
            if (count($patharr) > 2) {
                error('路由层级过多，不支持访问', 10001);
            }
            if (!empty($patharr)) {
                foreach ($patharr as $vo) {
                    if (1 !== preg_match('/^[A-Za-z0-9\-\_]+$/', (string)$vo)) {
                        error('请求url存在非法字符', 10001);
                    }
                }
                if (isset($patharr[0])) {
                    $this->ctrl = $patharr[0];
                    unset($patharr[0]);
                } else {
                    $this->ctrl = $default;
                }
                if (isset($patharr[1])) {
                    $this->action = $patharr[1];
                    unset($patharr[1]);
                } else {
                    $this->action = $default;
                }
            }
        }
    }
}
